<?php

class Twis_Template
{
    private $_vars = array();
    private $_config = null;
    private $_proxy = null;
    private $_url = null;

    public function __construct($config)
    {
        $this->_config = $config;
    }

    public function setProxy($proxy)
    {
        $this->_proxy = $proxy;
    }

    public function getProxy()
    {
        if(null === $this->_proxy) {
            throw new Exception('Proxy instance must be set');
        }
        return $this->_proxy;
    }

    public function setUrl($url)
    {
        $this->_url = $url;
    }

    public function getUrl()
    {
        if(null === $this->_url) {
            throw new Exception('Url instance must be set');
        }
        return $this->_url;
    }

    public function has($name)
    {
        $tplPath = $this->_config->get('tpl.path', './tpl');
        $tplFile = $tplPath . '/' . $name;
        if(file_exists($tplFile)) {
            return true;
        } else {
            return false;
        }
    }

    public function set($name, $value)
    {
        $this->_vars[$name] = $value;
        return $this;
    }

    public function render($name, $vars = array())
    {
        $vars = array_merge($this->_vars, $vars);

        $tplPath = $this->_config->get('tpl.path', './tpl');
        $tplCache = $this->_config->get('tpl.cache', './tmp/tpl');
        $debug = $this->_config->get('env.debug', true);

        // Set url
        $url = array();
        // $url['base'] = $this->_config->get('url.base', '/');
        $url['base'] = $this->getUrl()->getBaseUrl();
        $url['resource'] = $this->_config->get('url.resource', '/res');
        $vars['url'] = $url;

        // Env
        $loader = new Twig_Loader_Filesystem($tplPath);
        $twig = new Twig_Environment($loader, array(
          'cache' => $tplCache,
          'debug' => $debug,
          //'base_template_class' => 'Twis_Template_Base',
        ));

        // Add extension
        $twig->addExtension(new Twis_Template_Call());
        $twig->addExtension(new Twis_Template_Url());

        $twig->setContext('proxy', $this->getProxy());
        $twig->setContext('url', $this->getUrl());

        // Load template
        $template = $twig->loadTemplate($name);
        //$template->setContext('proxy', $this->getProxy());
        //$template->setContext('url', $this->getUrl());
        return $template->render($vars);
    }
}
